import { createStore, useStore as baseUseStore, Store } from "vuex"
import { setStorage } from "../util/cache"
import { InjectionKey } from "vue"
import { formatSingleData } from "@/hooks"
import type { article } from "@/hooks/useArticles"
import bus from "@/eventBus"

export const key: InjectionKey<Store<State>> = Symbol()
const html = document.querySelector("html")

export interface State {
  themeColor: string
  theme: string
  rootOpacity: string
  articles: Array<article>
  essays: Array<essay>
}

export type essay = {
  date: string
  content: string
}

export interface adminInfo {
  admin_passWord: string
  admin_userName: string
  name: string
  userType: string
}

export const store = createStore<State>({
  state: {
    themeColor: "#0EA9E3",
    theme: "light",
    rootOpacity: "1",
    articles: [],
    essays: [],
  },
  getters: {
    themeColor(state) {
      return state.themeColor
    },
  },
  mutations: {
    setEssays(state: State, val: Array<essay>) {
      state.essays = val
    },
    updateArticle(state, val: { data: string; id: number }) {
      const { id } = val
      for (let i = 0; i < state.articles.length; i++) {
        if (state.articles[i].id == id) {
          state.articles[i] = formatSingleData(val)
          break
        }
      }
    },
    setArticles(state: State, val: Array<article>) {
      state.articles.push(...val)
    },
    setRootOpacity(state: State, val: string) {
      state.rootOpacity = val
    },
    setThemeColor(state: State, val: string): void {
      //设置主题色
      document.documentElement.style.setProperty("--themeColor", val)
      state.themeColor = val
      setStorage("themeColor", val)
      bus.state.themeColor = val
    },

    setTheme(state: State, val: string): void {
      //设置主题
      state.theme = val
      bus.state.theme = val
      setStorage("theme", val)
      html.className = val
      document.body.className = val
    },
  },
})

export function useStore() {
  return baseUseStore(key)
}
